package com.clstu.homeworks;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Locale;
import java.util.Scanner;

public class Homework01 {
    public static void main(String[] args) {
        A a = new A();
        B b = new B(a);
        a.start();
        b.start();

    }
}
class A extends Thread{
    private boolean flag=true;
    public void setFlag(boolean flag){
        this.flag=flag;
    }

    @Override
    public void run() {
        while (flag){//通过flag控制退出线程
            System.out.println((int)(Math.random()*100));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("A线程退出");
    }
}

class B extends Thread implements KeyListener {
    private A a;
    char k;
    private final Scanner myScanner = new Scanner(System.in);
    public B(A a){
        this.a=a;
    }

    @Override
    public void run() {
        while (true){
            System.out.println("请输入你的指令（Q）表示退出");
            k = myScanner.next().toUpperCase(Locale.ROOT).charAt(0);
            if(k == 'Q'){
                a.setFlag(false);
                System.out.println("B进程结束");
                break;//break也可以退出线程
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {//注意调用方法
         if(e.getKeyCode()==KeyEvent.VK_Q){
             a.setFlag(false);
         }
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}